import axios, { AxiosError } from "axios";
import { Store } from "../main";
export interface ErrorRequest extends AxiosError {
  ErrorStatus: boolean;
}
export default class AbstractService {
  constructor(baseUrl: string) {
    this.baseServerUrl = baseUrl;
  }
  private baseServerUrl = "";
  private RequestInstance = axios.create({
    timeout: 5000,
  });
  protected async GetData(url: string, data: any = null) {
    return this.bulidRequset("get", url, data);
  }
  protected async PostData(url: string, data: any = null) {
    return this.bulidRequset("post", url, data);
  }
  protected async PutData(url: string, data: any = null) {
    return this.bulidRequset("put", url, data);
  }
  protected async DeleteData(url: string, data: any = null) {
    return this.bulidRequset("delete", url, data);
  }
  private async bulidRequset(method: "get" | "post" | "delete" | "put", url: string, data: any) {
    try {
      return await this.RequestInstance({
        method: method,
        url: this.baseServerUrl + url,
        data: method === "get" ? null : data,
        params: method === "get" ? data : null,
        headers: Store.Common.getRequestHeader(),
      }).then(res => res.data);
    } catch (err: any) {
      err["ErrorStatus"] = true;
      return Promise.resolve(err as ErrorRequest);
    }
  }
}
